
import { defineStore } from "pinia";
import { resetRouter } from "@/router";
// import { getLogin, reqUserinfo, reqLogout } from "@/api/business/user";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { constantRoutes } from "@/router";
import router from "@/router";
import { store } from "@/store";
import { getLogin, reqUserinfo } from "@/api/Newuser"
import { useStorage } from "@vueuse/core";

export const useUserStore = defineStore("user", () => {
  const permissionStore = usePermissionStoreHook();
  // 用户token
  const pinia_token = useStorage("pinia_token", "");
  // 用户基础、角色信息
  const pinia_userInfo = reactive({
    baseInfo: {},
    roleInfo: [],
  });

  const pinia_userTreelist = ref([]);
  // 设置token
  // 获取路由权限list

  function setuserTreelist(val: any) {
    pinia_userTreelist.value = val
  }

  function setToken(val: string) {
    pinia_token.value = val;
  }
  function setUserInfo(val: any) {
    // pinia_userInfo.baseInfo = val.base;
    console.log(pinia_userInfo.roleInfo);

    pinia_userInfo.roleInfo = val;
    console.log(pinia_userInfo.roleInfo, '角色信息');
  }

  // 登录
  function login(loginData: any) {
    return new Promise((resolve, reject) => {
      getLogin(loginData).then((res: any) => {
        if (res.code == 2000) {
          setToken(res.data.token);
          // ElMessage.success("登录成功");
          resolve(res.data.token);
        } else {
          reject(res)
          // ElMessage.error(res.msg);
        }
      });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、路由信息集合)
  function getUserInfo() {
    return new Promise((resolve, reject) => {
      reqUserinfo().then(async (res: any) => {
        console.log(res)
        if (res.code == 2000) {
          setUserInfo(res.data);
          resolve(res.data);
        } else {
          ElMessage.info(res.msg);
          return
        }
      });
    });
  }

  // user 登出
  function logout() {
    // reqLogout().then((res) => {
    //   if (res.code == 1) {
    //     ElMessage.success("退出中...");
    //     setTimeout(() => {
    //       resetStore();
    //     }, 500);
    //   }
    // });
    // ElMessage.success("退出中...");
    setTimeout(() => {
      resetStore();
    }, 1500);
  }

  // 清空缓存
  function resetStore() {
    location.reload(); // 清空路由
    pinia_token.value = "";
    permissionStore.pinia_menuList = constantRoutes;
    Object.assign(pinia_userInfo, { baseInfo: {}, roleInfo: [] });
  }

  return {
    pinia_userTreelist,
    setuserTreelist,
    pinia_token,
    pinia_userInfo,
    login,
    getUserInfo,
    logout,
    setToken,
    resetStore,
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}

